<template>
  <el-dialog title="协议详情" :model-value="modelValue" @update:model-value="(value) => emit('update:modelValue', value)" width="800px" append-to-body @close="handleClose">
    <div class="protocol-detail" v-loading="loading">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="通信协议ID">
          <span>{{ protocolDetail.protocolId }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="协议名称">
          <span>{{ protocolDetail.protocolName }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="产品名称">
          <span>{{ protocolDetail.productName }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="协议版本号">
          <span>{{ protocolDetail.protocolVersion }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="通信协议类型">
          <el-tag :type="getCommunicationTypeTag(protocolDetail.communicationType)">
            {{ getCommunicationTypeText(protocolDetail.communicationType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="编码格式">
          <el-tag type="info">{{ protocolDetail.encoding || 'UTF-8' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="protocolDetail.status === '1' ? 'success' : 'danger'">
            {{ protocolDetail.status === '1' ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          <span>{{ formatDate(protocolDetail.createTime) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">
          <span>{{ formatDate(protocolDetail.updateTime) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          <span>{{ protocolDetail.remark || '暂无备注' }}</span>
        </el-descriptions-item>
      </el-descriptions>
      
      <!-- 协议配置信息 -->
      <div class="config-section" v-if="protocolDetail.configInfo">
        <h4>协议配置</h4>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="重试次数">
            <span>{{ protocolDetail.configInfo.retryCount || 3 }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="心跳间隔">
            <span>{{ protocolDetail.configInfo.heartbeatInterval || 60 }}秒</span>
          </el-descriptions-item>
          <el-descriptions-item label="双向通信">
            <el-tag :type="protocolDetail.configInfo.bidirectional ? 'success' : 'info'">
              {{ protocolDetail.configInfo.bidirectional ? '支持' : '不支持' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="批量操作">
            <el-tag :type="protocolDetail.configInfo.batchOperation ? 'success' : 'info'">
              {{ protocolDetail.configInfo.batchOperation ? '支持' : '不支持' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <!-- 解析规则信息 -->
      <div class="parse-section" v-if="protocolDetail.parseRule">
        <h4>解析规则</h4>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="解析方式">
            <span>{{ getParseMethodText(protocolDetail.parseRule.parseMethod) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="解析脚本" v-if="protocolDetail.parseRule.parseScript">
            <el-input
              v-model="protocolDetail.parseRule.parseScript"
              type="textarea"
              :rows="4"
              readonly
              class="script-textarea"
            />
          </el-descriptions-item>
          <el-descriptions-item label="解析模板" v-if="protocolDetail.parseRule.parseTemplate">
            <el-input
              v-model="protocolDetail.parseRule.parseTemplate"
              type="textarea"
              :rows="3"
              readonly
              class="script-textarea"
            />
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关 闭</el-button>
        <el-button type="primary" @click="handleEdit">编 辑</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
// 移除远程API导入，改用本地模拟
// import { getProtocolDetail } from '@/api/IOT/protocolManage/protocolList'
import type { ProtocolInfo } from '@/api/IOT/protocolManage/protocolList/types'

// Props
interface Props {
  modelValue: boolean
  protocolId?: string | number
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  protocolId: ''
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'edit': [data: ProtocolInfo]
}>()

// 响应式数据
const loading = ref(false)
const protocolDetail = reactive<ProtocolInfo>({
  protocolId: '',
  protocolCode: '',
  protocolName: '',
  protocolType: '',
  transport: '',
  dataFormat: '',
  version: '',
  iconUrl: '',
  port: 0,
  timeout: 0,
  status: '1',
  description: '',
  remark: '',
  createTime: '',
  updateTime: ''
} as ProtocolInfo)

// 本地随机延迟
const delayRandom = (min = 200, max = 1500) => new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * (max - min + 1)) + min))

// 本地模拟获取协议详情
const getProtocolDetailMock = async (id: string | number) => {
  await delayRandom()
  const now = new Date()
  const communicationTypeList = ['HTTP', 'MQTT', 'TCP', 'UDP']
  const communicationType = communicationTypeList[Math.floor(Number(id) % communicationTypeList.length)]
  const data = {
    protocolId: String(id),
    protocolCode: `P-${id}`,
    protocolName: `协议-${id}`,
    protocolType: '标准协议',
    transport: communicationType,
    dataFormat: 'JSON',
    version: '1.0.0',
    iconUrl: '',
    port: 1883,
    timeout: 30,
    status: Math.random() > 0.2 ? '1' : '0',
    description: '这是本地模拟的协议详情描述',
    remark: '本地模拟数据',
    createTime: now.toISOString(),
    updateTime: now.toISOString(),
    // 供模板展示的额外字段
    productName: `产品-${(Number(id) % 5) + 1}`,
    protocolVersion: 'v1',
    communicationType,
    encoding: 'UTF-8',
    // 配置与解析规则
    configInfo: {
      retryCount: 3,
      heartbeatInterval: 60,
      bidirectional: Math.random() > 0.5,
      batchOperation: Math.random() > 0.5
    },
    parseRule: {
      parseMethod: 'script',
      parseScript: 'function parse(msg){ return JSON.parse(msg); }',
      parseTemplate: ''
    }
  }
  return { data }
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听协议ID变化
watch(
  () => props.protocolId,
  (newId) => {
    if (newId && visible.value) {
      fetchProtocolDetail()
    }
  },
  { immediate: true }
)

// 监听弹窗显示状态
watch(
  () => visible.value,
  (newVisible) => {
    if (newVisible && props.protocolId) {
      fetchProtocolDetail()
    }
  }
)

// 获取协议详情（使用本地模拟）
const fetchProtocolDetail = async () => {
  if (!props.protocolId) return
  try {
    loading.value = true
    const response = await getProtocolDetailMock(props.protocolId!)
    Object.assign(protocolDetail as any, response.data)
  } catch (error) {
    console.error('获取协议详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取通信协议类型标签
const getCommunicationTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    HTTP: 'success',
    MQTT: 'warning',
    TCP: 'info',
    UDP: 'primary'
  }
  return tagMap[type] || 'info'
}

// 获取通信协议类型文本
const getCommunicationTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    HTTP: 'HTTP',
    MQTT: 'MQTT',
    TCP: 'TCP',
    UDP: 'UDP'
  }
  return textMap[type] || type
}

// 获取解析方式文本
const getParseMethodText = (method: string) => {
  const textMap: Record<string, string> = {
    script: '脚本解析',
    template: '模板解析',
    rule: '规则解析'
  }
  return textMap[method] || method
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 编辑协议
const handleEdit = () => {
  emit('edit', protocolDetail)
  handleClose()
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.protocol-detail {
  max-height: 600px;
  overflow-y: auto;
}

.protocol-icon {
  width: 40px;
  height: 40px;
  border-radius: 4px;
}

.config-section,
.parse-section {
  margin-top: 16px;
}

.script-textarea :deep(.el-textarea__inner) {
  font-family: monospace;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>